package com.zpp.friend.service.user.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zpp.common.core.constants.Constants;
import com.zpp.common.core.domain.TableDataInfo;
import com.zpp.common.core.enums.ExamListType;
import com.zpp.common.core.enums.ResultCode;
import com.zpp.common.core.utils.ThreadLocalUtil;
import com.zpp.common.redis.service.RedisService;
import com.zpp.common.security.exception.ServiceException;
import com.zpp.friend.domain.exam.Exam;
import com.zpp.friend.domain.exam.dto.ExamQueryDTO;
import com.zpp.friend.domain.exam.vo.ExamVO;
import com.zpp.friend.domain.user.UserExam;
import com.zpp.friend.manager.ExamCacheManager;
import com.zpp.friend.mapper.exam.ExamMapper;
import com.zpp.friend.mapper.user.UserExamMapper;
import com.zpp.friend.service.user.IUserExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserExamServiceImpl implements IUserExamService {

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private ExamCacheManager examCacheManager;

    @Override
    public int enter(Long examId) {
        //1.检查竞赛是否存在
        Exam exam = examMapper.selectOne(new LambdaQueryWrapper<Exam>()
                .eq(Exam::getExamId, examId));
        if(exam == null){
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        //2.检查竞赛是否已经开赛
        if(exam.getStartTime().isBefore(LocalDateTime.now())) {
            throw new ServiceException(ResultCode.EXAM_STARTED);
        }

        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        //3.检查当前用户是否重复报名
        UserExam userExam = userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getExamId, examId)
                .eq(UserExam::getUserId, userId));
        if(userExam != null) {
            throw new ServiceException(ResultCode.USER_EXAM_HAS_ENTER);
        }

        //将已经报名的竞赛添加进redis中
        examCacheManager.addUserExamCache(userId,examId);

        //添加进数据库中
        userExam = new UserExam();
        userExam.setUserId(userId);
        userExam.setExamId(examId);
        return userExamMapper.insert(userExam);
    }

    //获取用户竞赛列表，先查询缓存（user:exam:list:userId），再查询数据库
    @Override
    public TableDataInfo list(ExamQueryDTO examQueryDTO) {

        Long userId = ThreadLocalUtil.get(Constants.USER_ID,Long.class);
        //获取缓存大小
        Long total = examCacheManager.getListSize(ExamListType.USER_EXAM_LIST.getValue(), userId);

        List<ExamVO> examVOList;
        if(total == null || total <= 0) {
            //从数据库中查询
            PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
            examVOList = userExamMapper.selectUserExamList(userId);
            //刷新缓存
            examCacheManager.refreshCache(ExamListType.USER_EXAM_LIST.getValue(), userId);
            //重新获取数量
            total = new PageInfo<>(examVOList).getTotal();
        }else{
            examQueryDTO.setType(ExamListType.USER_EXAM_LIST.getValue());
            //从缓存中获取数据
            examVOList = examCacheManager.getExamVOList(examQueryDTO,userId);
            //重新获取total
            total = examCacheManager.getListSize(ExamListType.USER_EXAM_LIST.getValue(), userId);
        }
        if(CollectionUtil.isEmpty(examVOList)) {
            return TableDataInfo.empty();
        }
        return TableDataInfo.success(examVOList, total);
    }
}
